package com.fowo.api.syncAmazon.core.sync;

import cn.hutool.core.collection.ListUtil;
import com.amazon.spapi.api.OrdersV0Api;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.orders.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.service.impl.AmazonSalesStatementServiceImpl;
import com.fowo.api.service.impl.ListingFatherServiceImpl;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.syncAmazon.core.AbstractAmazonSyncData;
import com.fowo.api.syncAmazon.entity.*;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.fowo.api.syncAmazon.service.FbaShipmentReportService;
import com.fowo.api.syncAmazon.service.impl.TmpSellOrderDetailServiceImpl;
import com.fowo.api.syncAmazon.service.impl.TmpSellOrderServiceImpl;
import com.fowo.api.syncAmazon.util.AmzDateUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.RateLimiter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @fileName: sellOrderSync
 * @Description: 销售订单
 * @Author: yyf
 * @Date: 2024/2/20 0020 13:55
 */
@Component
public class SellOrderSync extends AbstractAmazonSyncData {
    private ApiDefine apiDefine = ApiDefine.builder()
            .apiCode("sell_order")
            .initdate(1)
            .timeInterval(1)
            .timeIntervalType("day").build();

    @Override
    protected ApiDefine setApiDefine() {
        return apiDefine;
    }

    private List<TmpSellOrder> tmpSellOrderList;
    private List<TmpSellOrderDetail> tmpSellOrderDetailList;

    private OrderList orderList;
    private List<OrderItem> orderItemList;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private ListingFatherMapper listingFatherMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private TmpSellOrderServiceImpl tmpSellOrderService;
    @Resource
    private AmazonSalesStatementServiceImpl amazonSalesStatementService;
    @Resource
    private TmpSellOrderDetailServiceImpl tmpSellOrderDetailService;
    private final RateLimiter rateLimiter00167 = RateLimiter.create(0.01675);
    private final RateLimiter rateLimiter05 = RateLimiter.create(0.45);
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    @Override
    protected void requestData() throws Exception {
        // 获取卖家账号信息
        String platform = "Amazon";
        this.getAuthority(platform);

        List<ShopInfo> shopInfoList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform, "Amazon")
                .eq(ShopInfo::getSellerAuthStatus, "SQ01"));
        tmpSellOrderList = new ArrayList<>();
        tmpSellOrderDetailList = new ArrayList<>();

        // 清空临时表
        tmpSellOrderService.getBaseMapper().deleteAll();

        for (ShopInfo shopInfo : shopInfoList) {
            logger.info("正在拉取店铺："+shopInfo.getId()+"的订单");
            // 拉取销售订单
            orderList = requestOrderList(shopInfo);
            // 拉取销售订单详情
            orderItemList = new ArrayList<>();
            Map<String, List<OrderItem>> orderDetailMap = requestOrderDetailList(orderList, shopInfo);
            // 缓存
            download(orderDetailMap,shopInfo);

        }
        // 插入临时表中
        // 插入创建时间
        tmpSellOrderList.forEach(tmpSellOrder -> {
            tmpSellOrder.setCreateTime(new Date());
        });
        tmpSellOrderService.saveBatch(tmpSellOrderList);
        tmpSellOrderDetailList.forEach(r -> {
            r.setCreateTime(new Date());
        });
        tmpSellOrderDetailService.saveBatch(tmpSellOrderDetailList);

        // 写入同步数据量
        Integer dataVolume = apiRequestLog.getDataVolume() == null ? 0 : apiRequestLog.getDataVolume();
        apiRequestLog.setDataVolume(dataVolume+tmpSellOrderDetailList.size());
    }

    @Override
    protected void updateOrInsertData() {
        tmpSellOrderService.getBaseMapper().insertOrUpdateOrders();
        tmpSellOrderService.getBaseMapper().insertOrUpdateOrderItems();

        // 更新销售统计为空的sid和innerLID字段
        List<String> amazonOrderIds = tmpSellOrderList.stream().map(TmpSellOrder::getAmazonOrderId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(amazonOrderIds)){
            amazonTmpMapper.salesStatementBySellOrder(amazonOrderIds);
        }
    }

    private OrderList requestOrderList(ShopInfo shopInfo) throws InterruptedException {
        OrdersV0Api ordersV0Api = amazonUtil.getOrdersV0Api(entityAuthority, shopInfo,0.0167);
        List<String> marketplaceIds = Arrays.asList(shopInfo.getMarketplaceId().split(","));
        // 查询参数,具体信息参考文档
        // 以ISO 8601日期格式
        String pattern = "yyyy-MM-dd'T'HH:mm:ss";
        String createdAfter = null;
        String createdBefore = null;
        String lastUpdatedAfter = DateUtils.formatDate(startTime,pattern);
        String lastUpdatedBefore = DateUtils.formatDate(endTime,pattern);
        List<String> orderStatuses = null;
        List<String> fulfillmentChannels = null;
        List<String> paymentMethods = null;
        String buyerEmail = null;
        String sellerOrderId = null;
        Integer maxResultsPerPage = null;
        List<String> easyShipShipmentStatuses = null;
        String nextToken = null;
        List<String> amazonOrderIds = null;
        String actualFulfillmentSupplySourceId = null;
        Boolean isISPU = null;
        String storeChainStoreId = null;
        OrderList orderList = getAllOrders(ordersV0Api,marketplaceIds, createdAfter, createdBefore,
                lastUpdatedAfter, lastUpdatedBefore, orderStatuses, fulfillmentChannels, paymentMethods,
                buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses, nextToken,
                amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
        return orderList;
    }
    private Map<String,List<OrderItem>> requestOrderDetailList(OrderList orderList,ShopInfo shopInfo) throws InterruptedException {
        OrdersV0Api ordersV0Api = amazonUtil.getOrdersV0Api(entityAuthority, shopInfo,0.5);
        Map<String,List<OrderItem>> orderMap = new HashMap<>(orderList.size());

        int size = orderList.size();
        logger.info("---正在拉取订单详情，总共："+size+"---");
        for (Order order : orderList) {
            String amazonOrderId = order.getAmazonOrderId();
            String nextToken = null;
            boolean isContinue = true;
            int i = 3;
            List<OrderItem> orderItemListTmp = new ArrayList<>();

            while (isContinue){
                GetOrderItemsResponse orderItems = null;
                try {
                    rateLimiter05.acquire();
                    logger.info("还剩："+--size+"----");
                    orderItems = ordersV0Api.getOrderItems(order.getAmazonOrderId(), nextToken);
                } catch (ApiException e) {
                    if(e.getCode() == 429){
                        logger.info("出现请求频率过高，休眠60000ms！");
                        Thread.sleep(60000);
                        isContinue = true;

                        continue;
                    }else if(e.getMessage().contains("timeout")){
                        logger.info("出现超时异常，正在重试！");
                        Thread.sleep(10000);
                        isContinue = true;
                        i--;
                        if(i == 0){
                            throw new RuntimeException(e);
                        }
                        continue;
                    }else {
                        apiRequestLog.setErrorMessage("订单获取发生异常："+e.getMessage()+e.getResponseBody());
                        apiRequestLog.setStatus(ApiRequestLog.FAIL);
                        apiRequestLogService.getBaseMapper().updateById(apiRequestLog);
                        throw new RuntimeException(e);
                    }
                }
                OrderItemsList payload = orderItems.getPayload();
                nextToken = payload.getNextToken();
                orderItemListTmp.addAll(payload.getOrderItems());
                orderItemList.addAll(payload.getOrderItems());
                if (StringUtils.isBlank(nextToken)){
                    isContinue = false;
                }
            }
            if(orderMap.containsKey(amazonOrderId)){
                orderMap.get(amazonOrderId).addAll(orderItemListTmp);
            }else {
                orderMap.put(amazonOrderId,orderItemListTmp);
            }
        }
        return orderMap;
    }

    @Override
    protected <T> void download(T param, ShopInfo shop) throws IOException, IllegalArgumentException {
        // 泛型转换
        Map<String, List<OrderItem>> orderDetailMap = null;
        if(param instanceof Map<?,?>){
            orderDetailMap = (Map<String, List<OrderItem>>) param;
        } else {
            throw new IllegalArgumentException("Invalid parameter type. Expected: Map<String, List<OrderItem>>");
        }

        // 销售订单转为缓存对象
        orderToTmp(shop);
        // 销售订单其他信息
        List<FbaShipmentReport> fromShipmentReport = getFromShipmentReport();
        // 销售订单详情转为缓存对象
        try {
            orderDetailToTmp(orderDetailMap,shop);
            // 销售订单详情其他信息
            getDetailFromShipmentReport(fromShipmentReport);
            // 与listing_father做关联
            getDetailFromListingFather(shop);

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private void orderToTmp(ShopInfo shop){
        for(Order order : orderList){
            TmpSellOrder sellOrder = new TmpSellOrder();
            sellOrder.setAmazonOrderId(order.getAmazonOrderId());
            sellOrder.setSid(shop.getId());
            sellOrder.setCountry(shop.getMid());
            if(null != order.getBuyerInfo()){
                sellOrder.setBuyerName(order.getBuyerInfo().getBuyerName());
                sellOrder.setBuyerEmail(order.getBuyerInfo().getBuyerEmail());
            }
            if(null != order.getOrderTotal()){
                sellOrder.setOrderTotalAmount(order.getOrderTotal().getAmount());
                sellOrder.setCurrency(order.getOrderTotal().getCurrencyCode());
            }
            sellOrder.setPurchaseDateLocal(AmzDateUtils.getDatePlus(order.getPurchaseDate()));
            sellOrder.setRequestReviewStatus("0");
            sellOrder.setOrderStatus(order.getOrderStatus().getValue());
            if(null != order.getFulfillmentChannel()){
                sellOrder.setFulfillmentChannel(order.getFulfillmentChannel().getValue());
            }
            sellOrder.setIsAssessed(false);
            sellOrder.setIsMcfOrder(false);
            sellOrder.setIsReturnOrder(false);
            sellOrder.setIsReplacedOrder(StringUtils.isNotBlank(order.getReplacedOrderId()));
            sellOrder.setIsReplacementOrder(order.isIsReplacementOrder());
            sellOrder.setLastUpdateDate(AmzDateUtils.getDatePlus(order.getLastUpdateDate()));
            if(null != order.getShippingAddress()){
                sellOrder.setAddress(order.getShippingAddress().getAddressLine1());
                sellOrder.setPostalCode(order.getShippingAddress().getPostalCode());
                sellOrder.setName(order.getShippingAddress().getName());
                sellOrder.setPhone(order.getShippingAddress().getPhone());
            }
            if(null != order.getDefaultShipFromLocationAddress()){
                sellOrder.setShippingAddress(order.getDefaultShipFromLocationAddress().getAddressLine1());
            }
            sellOrder.setIsBusinessOrder(order.isIsBusinessOrder());
            sellOrder.setIsPrime(order.isIsPrime());
            sellOrder.setIsPremiumOrder(order.isIsPremiumOrder());
            sellOrder.setSalesChannel(order.getSalesChannel());
            sellOrder.setShipServiceLevel(order.getShipServiceLevel());
            sellOrder.setPaymentMethod(order.getPaymentMethod() == null? null : order.getPaymentMethod().getValue());
            sellOrder.setEarliestShipDate(AmzDateUtils.getDatePlus(order.getEarliestShipDate()));
            sellOrder.setLatestShipDate(AmzDateUtils.getDatePlus(order.getLatestShipDate()));
            sellOrder.setEarliestDeliveryDate(AmzDateUtils.getDatePlus(order.getEarliestDeliveryDate()));
            sellOrder.setLatestDeliveryDate(AmzDateUtils.getDatePlus(order.getLatestDeliveryDate()));

            tmpSellOrderList.add(sellOrder);

        }
    }
    @Resource
    private FbaShipmentReportService fbaShipmentReportService;
    private List<FbaShipmentReport> getFromShipmentReport(){
        if(tmpSellOrderList == null || tmpSellOrderList.size() == 0){
            return null;
        }
        List<String> amazonOrderIds = tmpSellOrderList.stream().map(TmpSellOrder::getAmazonOrderId).distinct().collect(Collectors.toList());
        List<FbaShipmentReport> fbaShipmentReportList = new ArrayList<>();
        for (List<String> amazonOrderId : ListUtils.partition(amazonOrderIds, 200)) {
            List<FbaShipmentReport> tmp = fbaShipmentReportService.list(Wrappers.lambdaQuery(FbaShipmentReport.class)
                    .in(FbaShipmentReport::getAmazonOrderId, amazonOrderId));
            fbaShipmentReportList.addAll(tmp);
        }

        for (TmpSellOrder tmpSellOrder : tmpSellOrderList) {
            Optional<FbaShipmentReport> exist = fbaShipmentReportList.stream()
                    .filter(r -> r.getAmazonOrderId().equals(tmpSellOrder.getAmazonOrderId())).findFirst();
            if(!exist.isPresent()){
                continue;
            }
            FbaShipmentReport fbaShipmentReport = exist.get();

            tmpSellOrder.setCarrier(fbaShipmentReport.getCarrier());
            tmpSellOrder.setTrackingNumber(fbaShipmentReport.getTrackingNumber());
            tmpSellOrder.setShipmentDate(fbaShipmentReport.getShipmentDate());
            tmpSellOrder.setPostedDate(fbaShipmentReport.getPaymentDate());
            BigDecimal itemPromotionDiscount = fbaShipmentReport.getItemPromotionDiscount();
            if(itemPromotionDiscount != null && itemPromotionDiscount != BigDecimal.ZERO){
                tmpSellOrder.setIsPromotion(true);
            }else {
                tmpSellOrder.setIsPromotion(false);
            }
            BigDecimal itemTax = fbaShipmentReport.getItemTax();
            if(itemTax != null && itemTax != BigDecimal.ZERO){
                tmpSellOrder.setTaxesIncluded(true);
            }else {
                tmpSellOrder.setTaxesIncluded(false);
            }
        }
        return fbaShipmentReportList;
    }

    private void getDetailFromShipmentReport(List<FbaShipmentReport> fbaShipmentReportList){
        if(fbaShipmentReportList == null || fbaShipmentReportList.size() == 0){
            return;
        }

        Map<String, List<FbaShipmentReport>> reportMap = fbaShipmentReportList.stream()
                .collect(Collectors.groupingBy(FbaShipmentReport::getAmazonOrderId));
        for (TmpSellOrderDetail tmpSellOrderDetail : tmpSellOrderDetailList) {

            String amazonOrderId = tmpSellOrderDetail.getAmazonOrderId();
            if(reportMap.containsKey(amazonOrderId)){
                List<FbaShipmentReport> fbaShipmentReportList1 = reportMap.get(amazonOrderId);
                Optional<FbaShipmentReport> exist = fbaShipmentReportList1.stream()
                        .filter(r -> r.getSku().equals(tmpSellOrderDetail.getSellerSku()))
                        .collect(Collectors.toList()).stream().findFirst();
                if(exist.isPresent()){
                    FbaShipmentReport fbaShipmentReport = exist.get();
                    tmpSellOrderDetail.setItemDiscount(fbaShipmentReport.getItemPromotionDiscount());
                    tmpSellOrderDetail.setItemPriceAmount(fbaShipmentReport.getItemPrice());
                    tmpSellOrderDetail.setItemTaxAmount(fbaShipmentReport.getItemTax());
                    tmpSellOrderDetail.setShippingTaxAmount(fbaShipmentReport.getShippingTax());
                }
            }
        }
    }
    @Resource
    private ListingFatherServiceImpl listingFatherService;
    private void getDetailFromListingFather(ShopInfo shopInfo){
        if(tmpSellOrderDetailList == null || tmpSellOrderDetailList.size() == 0){
            return;
        }
        List<ListingFather> listingFather = new ArrayList<>();
        for (List<TmpSellOrderDetail> tmpSellOrderDetails : ListUtil.partition(tmpSellOrderDetailList, 500)) {
            List<String> mskus = tmpSellOrderDetails.stream().map(TmpSellOrderDetail::getSellerSku).collect(Collectors.toList());
            List<ListingFather> tmp = listingFatherService.list(Wrappers.lambdaQuery(ListingFather.class).eq(ListingFather::getShop, shopInfo.getId())
                    .in(ListingFather::getMsku, mskus));
            listingFather.addAll(tmp);
        }

        for (TmpSellOrderDetail list : tmpSellOrderDetailList) {
            List<ListingFather> collect = listingFather.stream().filter(r -> r.getMsku().equals(list.getSellerSku())).collect(Collectors.toList());
            if (collect != null && collect.size() > 0){
                Optional<ListingFather> exist1 = collect.stream().filter(r -> r.getStatus().equals(1)).findFirst();
                Optional<ListingFather> exist2 = collect.stream().filter(r -> r.getStatus().equals(0)).findFirst();
                if (exist1.isPresent()){
                    list.setInnerLID(exist1.get().getId());
                }else if(exist2.isPresent()){
                    list.setInnerLID(exist2.get().getId());
                }else{
                    list.setInnerLID(collect.get(0).getId());
                }
            }
        }
    }

    private void orderDetailToTmp(Map<String, List<OrderItem>> order, ShopInfo shop) throws ParseException {
        if(orderItemList == null || orderItemList.size() == 0){
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<String> mskuList = orderItemList.stream().map(OrderItem::getSellerSKU).distinct().collect(Collectors.toList());
        Map<String,Long> mapTmp = new HashMap<>();
        for (List<String> mskus : Lists.partition(mskuList,200)) {
            // 根据msku和sid查询listing
            List<ListingFather> listingFathers = listingFatherMapper.selectList(Wrappers.lambdaQuery(ListingFather.class)
                    .eq(ListingFather::getShop, shop.getId())
                    .in(ListingFather::getMsku, mskuList));
            // 将msku和本地的产品id做映射
            for (ListingFather listingFather : listingFathers) {
                mapTmp.put(listingFather.getMsku(),listingFather.getPairProduct());
            }
        }

        // 整合要查询的本地产品id
        List<Long> productList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : mapTmp.entrySet()) {
            productList.add(entry.getValue());
        }

        // 查询本地产品
        Map<Long,Product> productMapId = new HashMap<>();
        for (List<Long> ids : Lists.partition(productList, 200)) {
            List<Product> products = productMapper.selectList(Wrappers.lambdaQuery(Product.class)
                    .in(Product::getId, ids));
            // 将本地产品和产品id做映射
            for (Product product : products) {
                productMapId.put(product.getId(),product);
            }
        }

        // 根据上面两个映射关系，将本地产品和msku做映射
        Map<String,Product> productMapMsku = new HashMap<>();
        for (String msku : mapTmp.keySet()) {
            Product product = productMapId.get(mapTmp.get(msku));
            productMapMsku.put(msku,product);
        }

        // 处理拉取到的销售订单详情
        for (String amazonOrderId : order.keySet()) {
            for (OrderItem orderItem : order.get(amazonOrderId)) {
                Product product = productMapMsku.get(orderItem.getSellerSKU());

                TmpSellOrderDetail detail = new TmpSellOrderDetail();
                if(product != null){
                    detail.setImg(product.getPicUrl());
                    detail.setProductName(product.getName());
                    detail.setSku(product.getSku());
                    detail.setProductId(product.getId());
                    detail.setCgPrice(product.getProcurementCost());
                }
                detail.setAmazonOrderId(amazonOrderId);
                detail.setTitle(orderItem.getTitle());
                detail.setAsin(orderItem.getASIN());
                detail.setAsinUrl("");
                detail.setSellerSku(orderItem.getSellerSKU());

                BigDecimal itemPrice = orderItem.getItemPrice()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getItemPrice().getAmount());
                detail.setUnitPriceAmount(itemPrice);
                String currencyCode = orderItem.getItemPrice()==null ? "" : orderItem.getItemPrice().getCurrencyCode();
                detail.setFeeCurrency(currencyCode);

                detail.setQuantityOrdered(orderItem.getQuantityOrdered());
                detail.setQuantityShipped(orderItem.getQuantityShipped());

                BigDecimal taxAmount = orderItem.getItemTax()==null?BigDecimal.ZERO: new BigDecimal(orderItem.getItemTax().getAmount());
                detail.setTaxAmount(taxAmount);

                BigDecimal shippingPrice = orderItem.getShippingPrice()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingPrice().getAmount());
                BigDecimal salesPriceAmount = itemPrice.add(taxAmount).add(shippingPrice);
                detail.setSalesPriceAmount(salesPriceAmount);

//            detail.setCgTransportCosts(product.getProcurementCost());
//            detail.setFbaShipmentAmount();
                detail.setPromotionAmount(orderItem.getPromotionDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscount().getAmount()));
                detail.setPromotionIds(orderItem.getPromotionIds()==null?"": Joiner.on(",").join(orderItem.getPromotionIds()));
//            detail.setCommissionAmount();
//            detail.setFeeCostAmount();
//            detail.setProfit();
                detail.setOrderItemId(orderItem.getOrderItemId());
//            detail.setItemPriceAmount(itemPrice);
//            detail.setItemTaxAmount(taxAmount);
                detail.setShippingPriceAmount(shippingPrice);
                detail.setShippingTaxAmount(orderItem.getShippingTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingTax().getAmount()));
                detail.setShippingDiscountAmount(orderItem.getShippingDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingDiscount().getAmount()));
                detail.setShippingDiscountTaxAmount(orderItem.getShippingDiscountTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getShippingDiscountTax().getAmount()));
                detail.setCodFeeAmount(orderItem.getCoDFee()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getCoDFee().getAmount()));
                detail.setPromotionDiscountAmount(orderItem.getPromotionDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscount().getAmount()));
                detail.setPromotionDiscountTaxAmount(orderItem.getPromotionDiscountTax()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getPromotionDiscountTax().getAmount()));
                detail.setCodFeeDiscountAmount(orderItem.getCoDFeeDiscount()==null?BigDecimal.ZERO:new BigDecimal(orderItem.getCoDFeeDiscount().getAmount()));
                if(null != orderItem.getBuyerInfo()){
                    final ItemBuyerInfo buyerInfo = orderItem.getBuyerInfo();
                    detail.setGiftWrapPriceAmount(buyerInfo.getGiftWrapPrice()==null?BigDecimal.ZERO:new BigDecimal(buyerInfo.getGiftWrapPrice().getAmount()));
                    detail.setGiftWrapTaxAmount(buyerInfo.getGiftWrapTax()==null?BigDecimal.ZERO:new BigDecimal(buyerInfo.getGiftWrapTax().getAmount()));
                    detail.setGiftMessageText(buyerInfo.getGiftMessageText());
                    detail.setGiftWrapLevel(buyerInfo.getGiftWrapLevel());
                }
                detail.setConditionNote(orderItem.getConditionNote());
                detail.setConditionId(orderItem.getConditionId());
                detail.setConditionSubtypeId(orderItem.getConditionSubtypeId());
                if(StringUtils.isNotBlank(orderItem.getScheduledDeliveryStartDate())){
                    detail.setScheduledDeliveryStartDate(simpleDateFormat.parse(orderItem.getScheduledDeliveryStartDate()
                            .replace("T"," ").replace("Z","")));
                }
                if(StringUtils.isNotBlank(orderItem.getScheduledDeliveryEndDate())){
                    detail.setScheduledDeliveryEndDate(simpleDateFormat.parse(orderItem.getScheduledDeliveryEndDate()
                            .replace("T"," ").replace("Z","")));
                }
                detail.setPriceDesignation(orderItem.getPriceDesignation());
                if(null != orderItem.getPointsGranted() && null != orderItem.getPointsGranted().getPointsMonetaryValue()){
                    BigDecimal pointsMonetaryValueAmount = orderItem.getPointsGranted().getPointsMonetaryValue().getAmount() == null
                            ? BigDecimal.ZERO
                            : new BigDecimal(orderItem.getPointsGranted().getPointsMonetaryValue().getAmount());
                    detail.setPointsMonetaryValueAmount(pointsMonetaryValueAmount);
                }

                tmpSellOrderDetailList.add(detail);
            }
        }
    }

    private OrderList getAllOrders(OrdersV0Api ordersV0Api, List<String> marketplaceIds, String createdAfter, String createdBefore, String lastUpdatedAfter, String lastUpdatedBefore, List<String> orderStatuses, List<String> fulfillmentChannels, List<String> paymentMethods, String buyerEmail, String sellerOrderId, Integer maxResultsPerPage, List<String> easyShipShipmentStatuses, String nextToken, List<String> amazonOrderIds, String actualFulfillmentSupplySourceId, Boolean isISPU, String storeChainStoreId) throws InterruptedException {

        OrderList orders = new OrderList();
        boolean isContinue = true;
        int i = 3;

        while (isContinue){
            rateLimiter00167.acquire();

            GetOrdersResponse response = null;
            try {
                logger.info("---正在拉取订单---");
                response = ordersV0Api.getOrders(marketplaceIds, createdAfter, createdBefore, lastUpdatedAfter, lastUpdatedBefore,
                        orderStatuses, fulfillmentChannels, paymentMethods, buyerEmail, sellerOrderId, maxResultsPerPage, easyShipShipmentStatuses,
                        nextToken, amazonOrderIds, actualFulfillmentSupplySourceId, isISPU, storeChainStoreId);
            } catch (ApiException e) {
                // 超时重试机制
                if(e.getMessage().contains("timeout")){
                    logger.info("--出现超时，正在重试--");
                    Thread.sleep(10000);
                    isContinue = true;
                    i--;
                    if (i == 0){
                        throw new RuntimeException(e);
                    }else {
                        continue;
                    }
                }else{
                    apiRequestLog.setErrorMessage("订单获取发生异常："+e.getMessage()+e.getResponseBody());
                    apiRequestLog.setStatus(ApiRequestLog.FAIL);
                    apiRequestLogService.getBaseMapper().updateById(apiRequestLog);
                    throw new RuntimeException(e);
                }
            }
            OrdersList payload = response.getPayload();

            orders.addAll(payload.getOrders());
            nextToken = payload.getNextToken();

            if (nextToken == null){
                isContinue = false;
            }
        }

        return orders;
    }
}
